import Schema from 'async-validator';
import type { Rules, InternalRuleItem, Value } from 'async-validator/dist-types/interface';
import { isEmpty } from 'lodash';

export const wrapperValidate = (fn: (_: any, value: string) => Promise<void>) => [
  {
    validator: fn,
  },
];

export const getValidate = (rules: Rules) => (values: any) => {
  if (isEmpty(rules)) {
    return {
      errors: [],
      fields: {},
    };
  }
  const validator = new Schema(rules);
  return validator
    .validate(values)
    .then(() => ({
      errors: [],
      fields: {},
    }))
    .catch(({ errors, fields }) => ({ errors, fields }));
};

type tv = (rule: InternalRuleItem, value: Value) => void;
export const validatorWrapper = (fn: tv) => (rule: InternalRuleItem, value: Value) => {
  const errors = [];
  try {
    fn.call(undefined, rule, value);
  } catch (error) {
    errors.push(error);
  }
  return errors;
};
